package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path/filepath"
	"time"
	"zg3/live-broadcasts/api/request"
	"zg3/live-broadcasts/global"
	"zg3/live-broadcasts/internal/dao"
	"zg3/live-broadcasts/internal/model"
)

func CreateLive(c *gin.Context) {
	var req request.CreateLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	ext := filepath.Ext(file.Filename)
	if ext != ".png" && ext != ".jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "图片类型必须为png或jpg",
			"data": false,
		})
		return
	}
	filename := time.Now().Format("20060102150405") + ext
	dst := "./static/upload/" + filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

	var findLive model.Live
	dao.ConditionQuery(&model.Live{UserId: c.GetUint("userId")}, &findLive)
	if findLive.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户已在直播中",
			"data": false,
		})
		return
	}
	live := model.Live{
		UserId: c.GetUint("userId"),
		Cover:  dst,
		Name:   req.Name,
		Sex:    req.Sex,
		Status: 0,
	}
	if !dao.Create(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "开启直播失败",
			"data": false,
		})
		return
	}
	var fans []model.Fans
	global.DB.Debug().Where("user_id = ?", c.GetUint("userId")).Find(&fans)

	content := fmt.Sprintf("你们喜欢的主播%d已经开播了,快来直播间%s", live.UserId, live.Name)
	for _, fan := range fans {
		notice := model.Notice{
			SendUserId:    fan.UserId,
			ReceiveUserId: fan.FansId,
			Content:       content,
		}
		dao.Create(&notice)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "开启直播成功",
		"data": live,
	})
	return
}
